<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>卡卷凑整计算器</title>
    <style>
        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 0 20px;
            font-family: "微软雅黑", sans-serif;
        }
        .section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 8px;
        }
        .product-row {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }
        .product-row input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        .remove-btn {
            background-color: #ff4444;
            color: white;
        }
        .remove-btn:hover {
            background-color: #cc0000;
        }
        .add-btn {
            background-color: #2ecc71;
            color: white;
        }
        .add-btn:hover {
            background-color: #27ae60;
        }
        .calculate-btn {
            background-color: #3498db;
            color: white;
            width: 100%;
            padding: 12px;
            font-size: 16px;
            margin-top: 10px;
        }
        .calculate-btn:hover {
            background-color: #2980b9;
        }
        #result {
            padding: 20px;
            border: 1px solid #eee;
            border-radius: 8px;
            margin-top: 20px;
            font-size: 14px;
            line-height: 1.6;
        }
        .result-item {
            margin-bottom: 8px;
            padding-left: 10px;
            border-left: 3px solid #3498db;
        }
        .total {
            font-weight: bold;
            margin-top: 10px;
            font-size: 16px;
            color: #2c3e50;
        }
        .error {
            color: #ff4444;
            font-weight: bold;
            margin-top: 10px;
        }
        h3 {
            margin-top: 0;
            color: #2c3e50;
            border-bottom: 2px solid #eee;
            padding-bottom: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>卡卷凑整计算器</h2>
        
        <!-- 商品输入区域 -->
        <div class="section">
            <h3>商品价格</h3>
            <div id="product-inputs">
                <div class="product-row">
                    <input type="number" class="product-price" placeholder="请输入商品价格（元）" min="0.01" step="0.01" value="5">
                    <button class="btn remove-btn">删除</button>
                </div>
                <div class="product-row">
                    <input type="number" class="product-price" placeholder="请输入商品价格（元）" min="0.01" step="0.01" value="10">
                    <button class="btn remove-btn">删除</button>
                </div>
            </div>
            <button id="add-product" class="btn add-btn">添加商品</button>
        </div>

        <!-- 卡券总额输入 -->
        <div class="section">
            <label for="total-voucher">卡券总额（元）：</label>
            <input type="number" id="total-voucher" placeholder="请输入卡券总金额" min="0.01" step="0.01" value="50">
        </div>

        <!-- 计算按钮 -->
        <button id="calculate-btn" class="btn calculate-btn">计算商品数量</button>

        <!-- 结果展示 -->
        <div id="result"></div>
    </div>

    <script>
        // 添加商品输入行
        document.getElementById('add-product').addEventListener('click', () => {
            const container = document.getElementById('product-inputs');
            const row = document.createElement('div');
            row.className = 'product-row';
            row.innerHTML = `
                <input type="number" class="product-price" placeholder="请输入商品价格（元）" min="0.01" step="0.01">
                <button class="btn remove-btn">删除</button>
            `;
            container.appendChild(row);
            
            // 绑定删除事件
            row.querySelector('.remove-btn').addEventListener('click', () => row.remove());
        });

        // 初始绑定删除事件
        document.querySelectorAll('.remove-btn').forEach(btn => {
            btn.addEventListener('click', () => btn.closest('.product-row').remove());
        });

        // 生成所有可能的组合（回溯法）
        function generateCombinations(prices, target) {
            const combinations = [];
            function backtrack(index, current, remaining) {
                if (index === prices.length) {
                    if (remaining === 0) combinations.push([...current]);
                    return;
                }
                const price = prices[index];
                const maxQty = Math.floor(remaining / price);
                for (let qty = 0; qty <= maxQty; qty++) {
                    current.push(qty);
                    backtrack(index + 1, current, remaining - qty * price);
                    current.pop();
                }
            }
            backtrack(0, [], target);
            return combinations;
        }

        // 计算按钮点击事件
        document.getElementById('calculate-btn').addEventListener('click', () => {
            const resultDiv = document.getElementById('result');
            resultDiv.innerHTML = '';

            // 收集有效商品价格
            const productPrices = [];
            document.querySelectorAll('.product-price').forEach(input => {
                const price = parseFloat(input.value);
                if (!isNaN(price) && price > 0) productPrices.push(price);
            });

            // 验证商品输入
            if (productPrices.length === 0) {
                resultDiv.innerHTML = '<div class="error">请至少输入一个有效商品价格！</div>';
                return;
            }

            // 收集并验证卡券总额
            const totalVoucher = parseFloat(document.getElementById('total-voucher').value);
            if (isNaN(totalVoucher) || totalVoucher <= 0) {
                resultDiv.innerHTML = '<div class="error">请输入有效的卡券总额！</div>';
                return;
            }

            // 排序商品价格（升序）并取出最大值
            const sortedPrices = [...productPrices].sort((a, b) => a - b);
            const lastPrice = sortedPrices.pop();

            // 寻找最优解（从最大可能的lastPrice数量开始尝试）
            let correctK = null;
            let correctCombination = null;
            for (let k = Math.floor(totalVoucher / lastPrice); k >= 0; k--) {
                const remaining = totalVoucher - k * lastPrice;
                const combinations = generateCombinations(sortedPrices, remaining);
                if (combinations.length > 0) {
                    correctK = k;
                    correctCombination = combinations[0];
                    break;
                }
            }

            // 展示结果
            if (correctCombination !== null) {
                let total = 0;
                
                // 展示前n-1个商品
                sortedPrices.forEach((price, idx) => {
                    const qty = correctCombination[idx];
                    const amount = price * qty;
                    total += amount;
                    
                    const itemDiv = document.createElement('div');
                    itemDiv.className = 'result-item';
                    itemDiv.textContent = 
                        `商品价格：${price.toFixed(2)}元 | 数量：${qty} | 小计：${amount.toFixed(2)}元`;
                    resultDiv.appendChild(itemDiv);
                });

                // 展示最后一个商品
                const lastQty = correctK;
                const lastAmount = lastPrice * lastQty;
                total += lastAmount;
                
                const lastItemDiv = document.createElement('div');
                lastItemDiv.className = 'result-item';
                lastItemDiv.textContent = 
                    `商品价格：${lastPrice.toFixed(2)}元 | 数量：${lastQty} | 小计：${lastAmount.toFixed(2)}元`;
                resultDiv.appendChild(lastItemDiv);

                // 展示总计
                const totalDiv = document.createElement('div');
                totalDiv.className = 'total';
                totalDiv.textContent = 
                    `总计：${total.toFixed(2)}元（与卡券总额一致：${totalVoucher.toFixed(2)}元）`;
                resultDiv.appendChild(totalDiv);
            } else {
                resultDiv.innerHTML = '<div class="error">无法用当前商品凑出卡券总额，请调整商品价格或卡券金额！</div>';
            }
        });
    </script>
</body>
</html>
